<?php

namespace System\Core;

if (!defined('BASEPATH')) die('Access Denied.');

/**
 * µMVC Framework (c) 2011.
 * 
 * PHP5 MVC Framework software for PHP 5.2.17 or later
 * 
 * @package         µMVC
 * @filename        system/core/basesingleton.class.php
 * @copyright       Lanz (c) 2011.
 * 
 */

/**
 * Base Signleton class
 * This is the base class for singleton classes. It can handle any number of
 * child singletons.
 * 
 * @package         µMVC
 * @subpackage      Core
 * @category        System
 */

class BaseSingleton 
{

    /**
     * Keeps track of all the instances of BaseSingleton child classes.
     * 
     * @var array of instances 
     */
    protected static $_instances = array();

    /**
     * Prevents direct creation of object.
     */
    protected function __construct() {}

    /**
     * Prevents cloning of the instance.
     */
    final private function __clone() {}
    
    /**
     * creates and returns the proper instance. Every child class is stored in
     * an internal array to help keep them as singletons.
     * @return object
     */
    final public static function instance()
    {      
        $className = get_called_class();
        
        if (!isset(self::$_instances[$className]))
        {
            self::$_instances[$className] = new $className();
        }
        
        return self::$_instances[$className];
    }
    
    /**
     * Checks if the class is instantiated or not, the drawback 
     * is that it will autoload the child class file just to check its state.
     * Use sparingly if at all.
     * 
     * @return boolean TRUE if instantiated, else FALSE.
     * 
     */
    final public static function isInstantiated()
    {
        $className = get_called_class();
        
        if (isset(self::$_instances[$className]))
        {
            return TRUE;
        }
        
        return FALSE;
    }
}

?>
